# -*- coding: utf-8 -*-
import logging
import traceback
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from apps.comments.forms import PostCommentForm
from apps.comments.models import CommentNotification
from apps.comments.templatetags.comments import render_comment
from apps.news.models import Record
from apps.users.models import UserProfile
from core.decorators import render
from core.enum import REQUEST_POST, RESPONSE_ERROR, RESPONSE_SUCCESS
from ..models import Comment
from services.vk import VKService

@csrf_exempt
@render(type="json")
def action(request):

    try:

        logger = logging.getLogger()

        if not request.method == REQUEST_POST:
            raise Exception("Only POST requests allowed")

        logger.info("POST Comment entry point")
        logger.info(request.POST)

        form = PostCommentForm(request.POST)
        if form.is_valid():

            logger.info("Form is valid!")

            comment = Comment.objects.create(
                user = request.user,
                message = form.cleaned_data.get('message', ''),
                uid = form.cleaned_data.get('uid', 0),
                parent = form.cleaned_data.get('parent', None),
                status = Comment.STATUS_PUBLISHED
            )

            logger.info("Comment created: %s" % comment.pk)

            url = ""
            try:
                url = Record.objects.get(pk = comment.uid).get_page_url()

                # create comments notification
                pks = Comment.objects.filter(uid = comment.uid).exclude(user = comment.user).values_list("user__pk", flat=True).distinct()
                thread_users = User.objects.filter(
                    pk__in = pks
                )
                for user in thread_users:
                    notification = CommentNotification.objects.get_or_create(
                        user = user,
                        record = Record.objects.get(pk = comment.uid)
                    )[0]
                    notification.comments += 1;
                    notification.save()

            except Exception, e:
                pass

            return {
                'code': RESPONSE_SUCCESS,
                'comment': render_comment(comment),
                'url': url
            }

        else:
            return {
                'code': RESPONSE_ERROR,
                'message': "Ошибка заполнения поля"#form.errors
            }

    except Exception, e:
        traceback.print_exc()
        return {
            'code': RESPONSE_ERROR,
            'message': "Внутренняя ошибка системы. Пожалуйста, попробуйте позже."
        }